package com.junzhiit.nengji.api.config;

import java.io.IOException;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Scope;

import com.junzhiit.nengji.api.rabbitmq.RabbitmqEnum;


@Configuration
@DependsOn("rabbitmqEnum") // 依赖依 RabbitmqEnum 类， 加此注解标明 rabbitmqEnum 类先加载后再加载本类
public class RabbitMQConfig {

	@Value("${spring.rabbitmq.host}")
	private String address;
	@Value("${spring.rabbitmq.port}")
	private String port;
	@Value("${spring.rabbitmq.username}")
	private String userName;
	@Value("${spring.rabbitmq.password}")
	private String password;
	
	/**
	 * 创建mq连接
	 * @return
	 * @throws IOException 
	 * @throws AmqpException 
	 */
	@Bean(name = "connectionFactory") 
	public ConnectionFactory connectionFactory() throws AmqpException, IOException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(address +":"+ port);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);
        connectionFactory.setPublisherReturns(true);
        String[] queueNames = RabbitmqEnum.Queues.getQueues();
        for (String queue : queueNames) {
        	connectionFactory.createConnection().createChannel(false).queueDeclare(queue, true, false, false, null);
        	connectionFactory.createConnection().createChannel(false).queueBind(queue, "amq.direct", queue);
		}
        return connectionFactory;
    }
	
	@Bean
	@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate() throws AmqpException, IOException {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setMandatory(true); // 如果未找到队列, 则强制将消息return给生产者, 而不是丢弃
        return template;
    }
}
